<template>
  <div class="genealogy-page">
    <!-- 左侧操作区域 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h3>家谱管理</h3>
      </div>
      <div class="sidebar-menu">
        <div class="menu-item" :class="{ active: activeFunction === 'familySelect' }" @click="activeFunction = 'familySelect'">
          <i class="fas fa-home"></i>
          <span>家族选择</span>
        </div>
        <div class="menu-item" :class="{ active: activeFunction === 'viewGenealogy' }" @click="activeFunction = 'viewGenealogy'">
          <i class="fas fa-sitemap"></i>
          <span>查看家谱</span>
        </div>
        <div class="menu-item" :class="{ active: activeFunction === 'personInfo' }" @click="showPersonInfo">
          <i class="fas fa-user"></i>
          <span>家谱人员信息</span>
        </div>
        <div class="menu-item" :class="{ active: activeFunction === 'eventQuery' }" @click="showAllEvents">
          <i class="fas fa-calendar-alt"></i>
          <span>成员事件查询</span>
        </div>
        <div class="menu-item" :class="{ active: activeFunction === 'relationshipManage' }" @click="showAllRelationships">
          <i class="fas fa-users"></i>
          <span>家谱成员关系管理</span>
        </div>
      </div>
      <div class="sidebar-footer">
        <button class="btn btn-primary" @click="goBack">
          <i class="fas fa-arrow-left me-2"></i>返回主页
        </button>
      </div>
    </div>

    <!-- 右侧展示区域 -->
    <div class="content-area">
      <!-- 顶部标题栏 -->
      <div class="content-header">
        <!-- 添加返回按钮 -->
        <div class="back-button d-block d-md-none" @click="goBack">
          <i class="fas fa-arrow-left"></i>
        </div>
        
        <h2>{{ genealogyTitle }}</h2>
        <div class="content-actions">
          <!-- 移除搜索和筛选按钮 -->
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-body">
        <div v-if="activeFunction === 'familySelect'" class="family-select">
          <h3>家族选择</h3>
          
          <!-- 搜索框 -->
          <div v-if="genealogies.length > 0" class="search-box mb-3">
            <div class="input-group">
              <input 
                type="text" 
                class="form-control" 
                placeholder="搜索家谱..." 
                v-model="genealogySearchQuery"
                @input="searchGenealogies"
              >
              <button class="btn btn-outline-secondary" type="button">
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>
          
          <!-- 加载中提示 -->
          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3">正在加载家族数据...</p>
          </div>
          
          <!-- 错误提示 -->
          <div v-else-if="error" class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ error }}
            <button class="btn btn-sm btn-outline-danger ms-3" @click="loadGenealogyData">
              <i class="fas fa-sync-alt me-1"></i>重试
            </button>
          </div>
          
          <!-- 无数据提示 -->
          <div v-else-if="genealogies.length === 0" class="family-placeholder">
            <i class="fas fa-home fa-3x mb-3"></i>
            <p>您还没有创建任何家族</p>
            <p class="text-muted small">当前用户ID: {{ userId || '未登录' }}</p>
            <button class="btn btn-primary mt-3" @click="showCreateGenealogyForm">
              <i class="fas fa-plus me-2"></i>创建新家谱
            </button>
          </div>
          
          <!-- 家族列表 -->
          <div v-else class="family-list">
            <div v-if="genealogySearchQuery && filteredGenealogies.length === 0" class="text-center py-4">
              <i class="fas fa-search fa-2x mb-3 text-muted"></i>
              <p>没有找到匹配的家谱</p>
              <button class="btn btn-sm btn-outline-secondary mt-2" @click="genealogySearchQuery = ''">
                <i class="fas fa-times me-1"></i>清除搜索
              </button>
            </div>
            <template v-else>
              <div v-for="genealogy in filteredGenealogies" :key="genealogy.genealogyId" 
                 class="family-item" @click="selectGenealogy(genealogy)">
              <div class="family-icon">
                <i class="fas fa-home"></i>
              </div>
              <div class="family-info">
                <h4>{{ genealogy.genealogyName }}</h4>
                <p>创建时间: {{ formatDate(genealogy.createTime) }}</p>
                <p v-if="genealogy.description" class="description">{{ genealogy.description }}</p>
              </div>
            </div>
            
            <!-- 创建新家族按钮 -->
            <div class="family-item add-family" @click="showCreateGenealogyForm">
              <div class="family-icon add-icon">
                <i class="fas fa-plus"></i>
              </div>
              <div class="family-info">
                <h4>创建新家谱</h4>
                <p>添加一个新的家谱记录</p>
              </div>
            </div>
            </template>
          </div>
          
          <!-- 创建家谱表单模态框 -->
          <div class="modal fade show" v-if="showGenealogyForm" style="display: block;">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title">创建新家谱</h5>
                  <button type="button" class="btn-close" @click="closeGenealogyForm"></button>
                </div>
                <div class="modal-body">
                  <form @submit.prevent="createNewGenealogy">
                    <div class="mb-3">
                      <label for="genealogyName" class="form-label">家谱名称</label>
                      <input 
                        type="text" 
                        class="form-control" 
                        id="genealogyName" 
                        v-model="newGenealogy.genealogyName" 
                        required
                        placeholder="请输入家谱名称"
                      >
                    </div>
                    <div class="mb-3">
                      <label for="genealogyDescription" class="form-label">家谱描述</label>
                      <textarea 
                        class="form-control" 
                        id="genealogyDescription" 
                        v-model="newGenealogy.description" 
                        rows="3"
                        placeholder="请输入家谱描述（选填）"
                      ></textarea>
                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" @click="closeGenealogyForm">取消</button>
                  <button type="button" class="btn btn-primary" @click="createNewGenealogy" :disabled="!newGenealogy.genealogyName">创建</button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 模态框背景遮罩 -->
          <div class="modal-backdrop fade show" v-if="showGenealogyForm"></div>
        </div>

        <div v-else-if="activeFunction === 'viewGenealogy'" class="genealogy-view">
          <h3>家谱树</h3>
          
          <!-- 显示当前选择的家谱 -->
          <div v-if="selectedGenealogyId && genealogyTitle" class="mb-3 d-flex align-items-center">
            <span class="text-muted">当前家族：</span>
            <span class="badge bg-primary ms-2">{{ genealogyTitle }}</span>
            <button class="btn btn-sm btn-outline-secondary ms-3" @click="activeFunction = 'familySelect'">
              <i class="fas fa-exchange-alt me-1"></i>切换家族
            </button>
            </div>
          
          <!-- 加载中提示 -->
          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3">正在加载家谱数据...</p>
          </div>
          
          <!-- 错误提示 -->
          <div v-else-if="error" class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ error }}
            <button class="btn btn-sm btn-outline-danger ms-3" @click="loadGenealogyTreeData">
              <i class="fas fa-sync-alt me-1"></i>重试
            </button>
          </div>
          
          <!-- 家谱树展示区域 -->
          <div v-else class="genealogy-tree-container">
            <div v-if="!treeReady" class="text-center py-5">
              <i class="fas fa-sitemap fa-3x mb-3 text-muted"></i>
              <p>正在生成家谱树...</p>
            </div>
            <div v-else-if="treeData.length === 0" class="text-center py-5">
              <i class="fas fa-exclamation-circle fa-3x mb-3 text-muted"></i>
              <p>当前家族暂无成员或关系数据</p>
              <p class="text-muted">请先添加家族成员和关系</p>
            </div>
            <div v-else class="family-tree">
              <div class="tree-container">
                <div v-if="treeData.length === 0" class="text-center py-5">
                  <i class="fas fa-exclamation-circle fa-3x mb-3 text-muted"></i>
                  <p>当前家族暂无成员或关系数据</p>
                  <p class="text-muted">请先添加家族成员和关系</p>
                </div>
                <template v-else>
                  <h4 class="tree-section-title">家族关系图</h4>
                  <p class="text-muted mb-4">显示该家族内所有有关系的成员</p>
                  
                  <div class="unified-tree-container">
                    <div class="family-members-container" :style="{ transform: `scale(${zoomLevel})` }">
                      <family-tree-node 
                        v-for="(node, index) in treeData" 
                        :key="index" 
                        :node="node" 
                        :format-date="formatDate"
                      />
                    </div>
                    
                    <!-- 缩放控制按钮 -->
                    <div class="tree-controls">
                      <div class="tree-control-btn" @click="zoomIn" title="放大">
                        <i class="fas fa-search-plus"></i>
                      </div>
                      <div class="tree-control-btn" @click="zoomOut" title="缩小">
                        <i class="fas fa-search-minus"></i>
                      </div>
                      <div class="tree-control-btn" @click="resetZoom" title="重置">
                        <i class="fas fa-redo"></i>
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>

        <div v-else-if="activeFunction === 'personInfo'" class="person-info">
          <h3>家谱人员信息</h3>
          
          <!-- 显示当前选择的家谱 -->
          <div v-if="selectedGenealogyId && genealogyTitle" class="mb-3 d-flex align-items-center">
            <span class="text-muted">当前家族：</span>
            <span class="badge bg-primary ms-2">{{ genealogyTitle }}</span>
            <button class="btn btn-sm btn-outline-secondary ms-3" @click="activeFunction = 'familySelect'">
              <i class="fas fa-exchange-alt me-1"></i>切换家族
            </button>
          </div>
          
          <!-- 加载中提示 -->
          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3">正在加载家谱人员数据...</p>
          </div>
          
          <!-- 错误提示 -->
          <div v-else-if="error" class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ error }}
            <button class="btn btn-sm btn-outline-danger ms-3" @click="showPersonInfo">
              <i class="fas fa-sync-alt me-1"></i>重试
            </button>
          </div>
          
          <!-- 显示人员列表 -->
          <div v-else-if="personList.length > 0">
            <div class="mb-3">
              <div class="input-group">
                <input type="text" class="form-control" placeholder="搜索人员..." v-model="personSearchQuery">
                <button class="btn btn-outline-secondary" type="button">
                  <i class="fas fa-search"></i>
                </button>
              </div>
              <button class="btn btn-success mt-2" @click="showAddPersonDialog">
                <i class="fas fa-plus me-1"></i>添加新成员
              </button>
            </div>
            
            <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>人员ID</th>
                  <th>家谱ID</th>
                  <th>用户ID</th>
                  <th>姓名</th>
                  <th>性别</th>
                  <th>出生日期</th>
                  <th>死亡日期</th>
                  <th>头像</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="person in filteredPersons" :key="person.personId">
                  <td>{{ person.personId }}</td>
                  <td>{{ person.genealogyId }}</td>
                  <td>{{ person.userId }}</td>
                  <td>{{ person.name }}</td>
                  <td>{{ person.sex }}</td>
                  <td>{{ person.birthDate ? new Date(person.birthDate).toLocaleDateString() : '' }}</td>
                  <td>{{ person.deathDate ? new Date(person.deathDate).toLocaleDateString() : '' }}</td>
                  <td>
                    <img v-if="person.avatar" :src="person.avatar" alt="头像" style="width:40px;height:40px;border-radius:50%;object-fit:cover;" />
                    <span v-else>无</span>
                  </td>
                  <td>
                    <button class="btn btn-sm btn-outline-primary me-1" title="编辑" @click="showEditPersonDialog(person)">
                      <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" title="删除" @click="confirmDeletePerson(person)">
                      <i class="fas fa-trash"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div v-else class="text-center py-5">
            <i class="fas fa-users fa-3x mb-3 text-muted"></i>
            <p>暂无成员信息</p>
            <button class="btn btn-primary mt-3" @click="showAddPersonDialog">
              <i class="fas fa-plus me-2"></i>添加新成员
            </button>
          </div>
          
          <!-- 人员编辑对话框 -->
          <div class="modal fade" :class="{ 'show d-block': showPersonDialog }" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title">{{ isNewPerson ? '添加新成员' : '编辑成员信息' }}</h5>
                  <button type="button" class="btn-close" @click="closePersonDialog" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <form>
                    <div class="mb-3">
                      <label for="personName" class="form-label">姓名</label>
                      <input type="text" class="form-control" id="personName" v-model="editingPerson.name" required>
                    </div>
                    <div class="mb-3">
                      <label for="personSex" class="form-label">性别</label>
                      <select class="form-select" id="personSex" v-model="editingPerson.sex" required>
                        <option value="" disabled>请选择性别</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                      </select>
                    </div>
                    <div class="mb-3">
                      <label for="birthDate" class="form-label">出生日期</label>
                      <input type="date" class="form-control" id="birthDate" v-model="editingPerson.birthDateStr">
                    </div>
                    <div class="mb-3">
                      <label for="deathDate" class="form-label">死亡日期</label>
                      <input type="date" class="form-control" id="deathDate" v-model="editingPerson.deathDateStr">
                    </div>
                    <div class="mb-3">
                      <label for="avatar" class="form-label">头像URL</label>
                      <input type="text" class="form-control" id="avatar" v-model="editingPerson.avatar" placeholder="请输入头像图片URL">
                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" @click="closePersonDialog">取消</button>
                  <button type="button" class="btn btn-primary" @click="savePerson">保存</button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 模态框背景遮罩 -->
          <div class="modal-backdrop fade show" v-if="showPersonDialog"></div>
        </div>

        <div v-else-if="activeFunction === 'eventQuery'" class="event-query">
          <h3>成员事件查询</h3>
          
          <!-- 显示当前选择的家谱 -->
          <div v-if="selectedGenealogyId && genealogyTitle" class="mb-3 d-flex align-items-center">
            <span class="text-muted">当前家族：</span>
            <span class="badge bg-primary ms-2">{{ genealogyTitle }}</span>
          </div>
          
          <!-- 加载中提示 -->
          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3">正在加载事件数据...</p>
          </div>
          
          <!-- 错误提示 -->
          <div v-else-if="error" class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ error }}
            <button class="btn btn-sm btn-outline-danger ms-3" @click="showAllEvents">
              <i class="fas fa-sync-alt me-1"></i>重试
            </button>
          </div>
          
          <!-- 显示事件列表 -->
          <div v-else-if="allEvents.length > 0">
            <div class="mb-3">
              <div class="input-group">
                <input type="text" class="form-control" placeholder="搜索事件..." v-model="eventSearchQuery">
                <button class="btn btn-outline-secondary" type="button">
                  <i class="fas fa-search"></i>
                </button>
              </div>
            </div>
            
            <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>事件ID</th>
                  <th>人员姓名</th>
                  <th>事件类型</th>
                  <th>事件时间</th>
                  <th>事件描述</th>
                  <th>附件</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="event in filteredEvents" :key="event.eventId">
                  <td>{{ event.eventId }}</td>
                  <td>{{ getPersonName(event.personId) }}</td>
                  <td>{{ event.eventType }}</td>
                  <td>{{ event.eventTime ? new Date(event.eventTime).toLocaleString() : '' }}</td>
                  <td>{{ event.description }}</td>
                  <td>
                    <a v-if="event.eventAttachment" :href="event.eventAttachment" target="_blank">查看附件</a>
                    <span v-else>无</span>
                  </td>
                  <td>
                    <button class="btn btn-sm btn-outline-primary me-1" @click="showEditEventDialog(event)">
                      <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" @click="confirmDeleteEvent(event)">
                      <i class="fas fa-trash"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div v-else class="text-center py-5">
            <i class="fas fa-calendar-times fa-3x mb-3 text-muted"></i>
            <p>当前家族暂无事件记录</p>
          </div>
          
          <!-- 添加事件按钮 -->
          <div class="mt-3">
            <button class="btn btn-primary" @click="showAddEventDialog">
              <i class="fas fa-plus me-1"></i>添加新事件
            </button>
          </div>
          
          <!-- 事件编辑对话框 -->
          <div class="modal fade" :class="{ 'show d-block': showEventDialog }" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title">{{ isNewEvent ? '添加新事件' : '编辑事件信息' }}</h5>
                  <button type="button" class="btn-close" @click="closeEventDialog" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <form>
                    <div class="mb-3">
                      <label for="eventPersonId" class="form-label">关联人员</label>
                      <select class="form-select" id="eventPersonId" v-model="editingEvent.personId" required>
                        <option value="" disabled>请选择关联人员</option>
                        <option v-for="person in personList" :key="person.personId" :value="person.personId">
                          {{ person.name }}
                        </option>
                      </select>
                    </div>
                    <div class="mb-3">
                      <label for="eventType" class="form-label">事件类型</label>
                      <select class="form-select" id="eventType" v-model="editingEvent.eventType" required>
                        <option value="" disabled>请选择事件类型</option>
                        <option v-for="type in eventTypes" :key="type" :value="type">{{ type }}</option>
                      </select>
                    </div>
                    <div class="mb-3">
                      <label for="eventTime" class="form-label">事件时间</label>
                      <input type="datetime-local" class="form-control" id="eventTime" v-model="editingEvent.eventTimeStr">
                    </div>
                    <div class="mb-3">
                      <label for="eventDescription" class="form-label">事件描述</label>
                      <textarea class="form-control" id="eventDescription" v-model="editingEvent.description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                      <label for="eventAttachment" class="form-label">附件链接</label>
                      <input type="text" class="form-control" id="eventAttachment" v-model="editingEvent.eventAttachment" placeholder="请输入附件链接">
                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" @click="closeEventDialog">取消</button>
                  <button type="button" class="btn btn-primary" @click="saveEvent">保存</button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 模态框背景遮罩 -->
          <div class="modal-backdrop fade show" v-if="showEventDialog"></div>
        </div>

        <div v-else-if="activeFunction === 'relationshipManage'" class="relationship-manage">
          <h3>家谱成员关系管理</h3>
          
          <!-- 显示当前选择的家谱 -->
          <div v-if="selectedGenealogyId && genealogyTitle" class="mb-3 d-flex align-items-center">
            <span class="text-muted">当前家族：</span>
            <span class="badge bg-primary ms-2">{{ genealogyTitle }}</span>
        </div>
          
          <!-- 加载中提示 -->
          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
      </div>
            <p class="mt-3">正在加载关系数据...</p>
          </div>
          
          <!-- 错误提示 -->
          <div v-else-if="error" class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ error }}
            <button class="btn btn-sm btn-outline-danger ms-3" @click="showAllRelationships">
              <i class="fas fa-sync-alt me-1"></i>重试
            </button>
          </div>
          
          <!-- 显示关系列表 -->
          <div v-else-if="relationships.length > 0">
            <div class="mb-3">
              <div class="input-group">
                <input type="text" class="form-control" placeholder="搜索关系..." v-model="relationshipSearchQuery">
                <button class="btn btn-outline-secondary" type="button">
                  <i class="fas fa-search"></i>
                </button>
              </div>
              <button class="btn btn-success mt-2" @click="showAddRelationshipDialog">
                <i class="fas fa-plus me-1"></i>添加新关系
              </button>
            </div>
            
            <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>关系ID</th>
                  <th>第一人</th>
                  <th>关系类型</th>
                  <th>第二人</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="relationship in filteredRelationships" :key="relationship.relationshipId">
                  <td>{{ relationship.relationshipId }}</td>
                  <td>{{ getPersonName(relationship.personId1) }}</td>
                  <td>{{ relationship.relationshipType }}</td>
                  <td>{{ getPersonName(relationship.personId2) }}</td>
                  <td>
                    <button class="btn btn-sm btn-outline-primary me-1" title="编辑" @click="showEditRelationshipDialog(relationship)">
                      <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" title="删除" @click="confirmDeleteRelationship(relationship)">
                      <i class="fas fa-trash"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div v-else class="text-center py-5">
            <i class="fas fa-link fa-3x mb-3 text-muted"></i>
            <p>当前家族暂无成员关系记录</p>
            <button class="btn btn-primary mt-3" @click="showAddRelationshipDialog">
              <i class="fas fa-plus me-2"></i>添加新关系
            </button>
          </div>
          
          <!-- 关系编辑对话框 -->
          <div class="modal fade" :class="{ 'show d-block': showEditDialog }" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title">{{ isNewRelationship ? '添加新关系' : '编辑关系' }}</h5>
                  <button type="button" class="btn-close" @click="closeEditDialog" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <form>
                    <div class="mb-3">
                      <label for="person1" class="form-label">第一人</label>
                      <select class="form-select" id="person1" v-model="editingRelationship.personId1" required>
                        <option value="" disabled>请选择人员</option>
                        <option v-for="person in personList" :key="person.personId" :value="person.personId">
                          {{ person.name }}
                        </option>
                      </select>
                    </div>
                    <div class="mb-3">
                      <label for="relationshipType" class="form-label">关系类型</label>
                      <select class="form-select" id="relationshipType" v-model="editingRelationship.relationshipType" required>
                        <option value="" disabled>请选择关系类型</option>
                        <option v-for="type in relationshipTypes" :key="type" :value="type">
                          {{ type }}
                        </option>
                      </select>
                    </div>
                    <div class="mb-3">
                      <label for="person2" class="form-label">第二人</label>
                      <select class="form-select" id="person2" v-model="editingRelationship.personId2" required>
                        <option value="" disabled>请选择人员</option>
                        <option v-for="person in personList" :key="person.personId" :value="person.personId">
                          {{ person.name }}
                        </option>
                      </select>
                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" @click="closeEditDialog">取消</button>
                  <button type="button" class="btn btn-primary" @click="saveRelationship">保存</button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 模态框背景遮罩 -->
          <div class="modal-backdrop fade show" v-if="showEditDialog"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import FamilyTreeNode from '../components/FamilyTreeNode.vue';

export default {
  name: 'GenealogyView',
  components: {
    FamilyTreeNode
  },
  data() {
    return {
      activeFunction: 'familySelect', // 默认显示家族选择
      genealogyTitle: '我的家谱', // 默认标题
      genealogyId: null,
      userId: localStorage.getItem('userId'),
      genealogies: [],
      loading: false,
      error: null,
      debugInfo: '', // 添加调试信息字段
      newGenealogy: {
        genealogyName: '',
        description: ''
      },
      showGenealogyForm: false,
      selectedGenealogyId: null,
      personList: [],
      personSearchQuery: '', // 添加人员搜索查询
      allEvents: [],
      eventSearchQuery: '',
      relationships: [],
      relationshipSearchQuery: '',
      // 添加编辑关系相关数据
      showEditDialog: false,
      editingRelationship: {
        relationshipId: null,
        personId1: null,
        personId2: null,
        relationshipType: ''
      },
      relationshipTypes: ['父子', '母子', '夫妻', '兄妹', '兄弟', '姐妹', '祖孙', '其他'],
      isNewRelationship: false,
      // 添加编辑人员相关数据
      showPersonDialog: false,
      editingPerson: {
        personId: null,
        genealogyId: null,
        userId: null,
        name: '',
        sex: '',
        birthDateStr: '',
        deathDateStr: '',
        avatar: ''
      },
      isNewPerson: false,
      // 添加编辑事件相关数据
      showEventDialog: false,
      editingEvent: {
        eventId: null,
        personId: '',
        eventType: '',
        eventTimeStr: '',
        description: '',
        eventAttachment: ''
      },
      isNewEvent: false,
      eventTypes: ['出生', '死亡', '结婚', '离婚', '入学', '毕业', '就业', '退休', '迁居', '其他'],
      treeData: [],
      treeReady: false,
      genealogySearchQuery: '',
      zoomLevel: 1
    }
  },
  created() {
    // 从路由参数获取家谱ID
    this.genealogyId = this.$route.params.id;
    
    // 加载家谱数据
    this.loadGenealogyData();
    
    // 输出用户ID，确认是否正确获取
    console.log('当前用户ID:', this.userId);
  },
  methods: {
    async loadGenealogyData() {
      this.loading = true;
      this.error = null;
      
      // 检查用户ID是否存在
      if (!this.userId) {
        this.error = '用户未登录，请先登录';
        this.loading = false;
        return;
      }
      
      try {
        console.log('开始请求家谱数据...');
        // 添加超时设置
        const response = await axios.get('http://localhost:8080/genealogy/selectAll', { 
          timeout: 5000 // 5秒超时
        });
        console.log('API响应:', response);
        
        if (response && response.data && response.data.code === '200') {
          console.log('获取到的原始数据:', response.data.data);
          
          // 检查数据是否为数组
          if (!Array.isArray(response.data.data)) {
            this.error = '数据格式错误';
            return;
          }
          
          // 显示所有家谱数据，不进行过滤
          this.genealogies = response.data.data.map(genealogy => {
            console.log('家谱数据项:', genealogy);
            return genealogy;
          });
          
          console.log('处理后的家谱数据:', this.genealogies);
          
          // 如果有路由参数中的家谱ID，则选择该家谱
          if (this.genealogyId && this.genealogies.length > 0) {
            const selectedGenealogy = this.genealogies.find(
              g => g && g.genealogyId && g.genealogyId.toString() === this.genealogyId.toString()
            );
            
            if (selectedGenealogy) {
              this.selectGenealogy(selectedGenealogy);
            }
          }
        } else {
          this.error = (response && response.data && response.data.msg) || '获取家谱数据失败';
        }
      } catch (error) {
        console.error('加载家谱数据失败:', error);
        if (error.code === 'ECONNABORTED') {
          this.error = '请求超时，请检查后端服务是否正常运行';
        } else if (error.message && error.message.includes('Network Error')) {
          this.error = '网络错误，请确保后端服务已启动';
        } else {
        this.error = '网络错误，请稍后重试';
        }
      } finally {
        this.loading = false;
      }
    },
    selectGenealogy(genealogy) {
      this.selectedGenealogyId = genealogy.genealogyId;
      this.genealogyTitle = genealogy.genealogyName;
      this.activeFunction = 'viewGenealogy';
      
      // 切换家谱时显示提示
      // alert(`已选择家谱：${genealogy.genealogyName}`);
      
      // 加载家谱树数据
      this.loadGenealogyTreeData();
    },
    async createNewGenealogy() {
      if (!this.userId) {
        this.error = '用户未登录，无法创建家谱';
        return;
      }
      
      // 创建新家谱
      try {
        this.loading = true;
        
        const newGenealogy = {
          genealogyName: this.newGenealogy.genealogyName,
          description: this.newGenealogy.description,
          createTime: new Date().toISOString()
        };
        
        console.log('创建新家谱:', newGenealogy);
        
        const response = await axios.post('http://localhost:8080/genealogy/add', newGenealogy);
        
        if (response.data && response.data.code === '200') {
          alert('家谱创建成功！');
          // 关闭表单
          this.closeGenealogyForm();
          // 重置表单
          this.newGenealogy = {
            genealogyName: '',
            description: ''
          };
          // 重新加载家谱数据
          this.loadGenealogyData();
        } else {
          this.error = (response.data && response.data.msg) || '创建家谱失败';
          console.error('创建家谱失败:', response);
        }
      } catch (error) {
        console.error('创建家谱错误:', error);
        this.error = '创建家谱失败: ' + (error.message || '未知错误');
      } finally {
        this.loading = false;
      }
    },
    formatDate(dateString) {
      if (!dateString) return '';
      
      try {
      const date = new Date(dateString);
        if (isNaN(date.getTime())) return ''; // 无效日期
        
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
      } catch (e) {
        console.error('日期格式化错误:', e);
        return '';
      }
    },
    goBack() {
      this.$router.push('/home');
    },
    async showPersonInfo() {
      if (!this.selectedGenealogyId) {
        alert('请先选择家族');
        this.personList = [];
        return;
      }
      
      this.activeFunction = 'personInfo';
      this.loading = true; // 添加加载状态
      
      try {
        // 添加超时设置
        const res = await axios.get(`http://localhost:8080/genealogyPerson/selectByGenealogyId/${this.selectedGenealogyId}`, {
          timeout: 5000 // 5秒超时
        });
        if (res.data.code === '200') {
          this.personList = res.data.data;
          console.log('获取到的人员列表：', this.personList);
          if (this.personList && this.personList.length > 0) {
            console.log('第一个人员的性别值：', this.personList[0].sex);
            console.log('第一个人员的性别类型：', typeof this.personList[0].sex);
          }
        } else {
          this.personList = [];
          this.error = res.data.msg || '获取家谱成员失败'; // 使用error而不是alert
        }
      } catch (e) {
        console.error('获取家谱成员数据出错:', e);
        this.personList = [];
        if (e.code === 'ECONNABORTED') {
          this.error = '请求超时，请检查后端服务是否正常运行';
        } else if (e.message && e.message.includes('Network Error')) {
          this.error = '网络错误，请确保后端服务已启动';
        } else {
          this.error = '网络错误，无法获取家谱成员数据';
        }
      } finally {
        this.loading = false;
      }
    },
    async showAllEvents() {
      if (!this.selectedGenealogyId) {
        alert('请先选择家族');
        return;
      }
      
      this.activeFunction = 'eventQuery';
      this.loading = true;
      this.error = null;
      
      try {
        // 先获取家族所有成员
        if (this.personList.length === 0) {
          const personRes = await axios.get(`http://localhost:8080/genealogyPerson/selectByGenealogyId/${this.selectedGenealogyId}`, {
            timeout: 5000
          });
          
          if (personRes.data.code === '200') {
            this.personList = personRes.data.data;
          } else {
            throw new Error(personRes.data.msg || '获取家谱成员失败');
          }
        }
        
        // 如果没有成员，直接返回
        if (this.personList.length === 0) {
          this.allEvents = [];
          return;
        }
        
        // 获取所有事件
        const eventPromises = this.personList.map(person => 
          axios.get(`http://localhost:8080/personEvent/selectByPersonId/${person.personId}`, {
            timeout: 5000
          })
        );
        
        const eventResults = await Promise.all(eventPromises);
        
        // 合并所有事件
        this.allEvents = eventResults
          .filter(res => res.data.code === '200' && Array.isArray(res.data.data))
          .flatMap(res => res.data.data);
        
        console.log('获取到的所有事件：', this.allEvents);
      } catch (e) {
        console.error('获取事件数据出错:', e);
        this.allEvents = [];
        if (e.code === 'ECONNABORTED') {
          this.error = '请求超时，请检查后端服务是否正常运行';
        } else if (e.message && e.message.includes('Network Error')) {
          this.error = '网络错误，请确保后端服务已启动';
        } else {
          this.error = e.message || '网络错误，无法获取事件数据';
        }
      } finally {
        this.loading = false;
      }
    },
    async showAllRelationships() {
      if (!this.selectedGenealogyId) {
        alert('请先选择家族');
        return;
      }
      
      this.activeFunction = 'relationshipManage';
      this.loading = true;
      this.error = null;
      
      try {
        // 先获取家族所有成员
        if (this.personList.length === 0) {
          const personRes = await axios.get(`http://localhost:8080/genealogyPerson/selectByGenealogyId/${this.selectedGenealogyId}`, {
            timeout: 5000
          });
          
          if (personRes.data.code === '200') {
            this.personList = personRes.data.data;
          } else {
            throw new Error(personRes.data.msg || '获取家谱成员失败');
          }
        }
        
        // 如果没有成员，直接返回
        if (this.personList.length === 0) {
          this.relationships = [];
          return;
        }
        
        // 获取所有关系
        // 由于没有直接按家谱ID查询关系的API，我们需要通过成员ID查询
        // 我们可以查询所有关系，然后过滤出当前家族的成员之间的关系
        const response = await axios.get('http://localhost:8080/personRelationship/selectAll', {
          timeout: 5000
        });
        
        if (response.data.code === '200') {
          // 获取当前家族所有成员的ID
          const familyMemberIds = this.personList.map(person => person.personId);
          
          // 过滤出当前家族成员之间的关系
          this.relationships = response.data.data.filter(relationship => 
            familyMemberIds.includes(relationship.personId1) && 
            familyMemberIds.includes(relationship.personId2)
          );
          
          console.log('获取到的家族成员关系：', this.relationships);
        } else {
          throw new Error(response.data.msg || '获取关系数据失败');
        }
      } catch (e) {
        console.error('获取关系数据出错:', e);
        this.relationships = [];
        if (e.code === 'ECONNABORTED') {
          this.error = '请求超时，请检查后端服务是否正常运行';
        } else if (e.message && e.message.includes('Network Error')) {
          this.error = '网络错误，请确保后端服务已启动';
        } else {
          this.error = e.message || '网络错误，无法获取关系数据';
        }
      } finally {
        this.loading = false;
      }
    },
    // 根据人员ID获取人员姓名
    getPersonName(personId) {
      const person = this.personList.find(p => p.personId === personId);
      return person ? person.name : `未知(ID: ${personId})`;
    },
    
    // 显示添加新关系对话框
    showAddRelationshipDialog() {
      this.isNewRelationship = true;
      this.editingRelationship = {
        relationshipId: null,
        personId1: '',
        personId2: '',
        relationshipType: ''
      };
      this.showEditDialog = true;
    },
    
    // 显示编辑关系对话框
    showEditRelationshipDialog(relationship) {
      this.isNewRelationship = false;
      // 创建一个新对象，避免直接修改原对象
      this.editingRelationship = {
        relationshipId: relationship.relationshipId,
        personId1: relationship.personId1,
        personId2: relationship.personId2,
        relationshipType: relationship.relationshipType
      };
      this.showEditDialog = true;
    },
    
    // 关闭编辑对话框
    closeEditDialog() {
      this.showEditDialog = false;
    },
    
    // 保存关系
    async saveRelationship() {
      // 验证表单
      if (!this.editingRelationship.personId1 || 
          !this.editingRelationship.personId2 || 
          !this.editingRelationship.relationshipType) {
        alert('请填写完整的关系信息');
        return;
      }
      
      try {
        let response;
        
        if (this.isNewRelationship) {
          // 添加新关系
          response = await axios.post('http://localhost:8080/personRelationship/add', this.editingRelationship, {
            timeout: 5000
          });
        } else {
          // 更新现有关系
          response = await axios.put('http://localhost:8080/personRelationship/update', this.editingRelationship, {
            timeout: 5000
          });
        }
        
        if (response.data && response.data.code === '200') {
          // 关闭对话框
          this.closeEditDialog();
          // 重新加载关系数据
          this.showAllRelationships();
          alert(this.isNewRelationship ? '添加成功' : '更新成功');
        } else {
          alert((response.data && response.data.msg) || '操作失败');
        }
      } catch (e) {
        console.error('保存关系数据出错:', e);
        alert('网络错误，请稍后重试');
      }
    },
    
    // 确认删除关系
    confirmDeleteRelationship(relationship) {
      if (confirm(`确定要删除 ${this.getPersonName(relationship.personId1)} 和 ${this.getPersonName(relationship.personId2)} 之间的 ${relationship.relationshipType} 关系吗？`)) {
        this.deleteRelationship(relationship.relationshipId);
      }
    },
    
    // 删除关系
    async deleteRelationship(relationshipId) {
      try {
        const response = await axios.delete(`http://localhost:8080/personRelationship/deleteById/${relationshipId}`, {
          timeout: 5000
        });
        
        if (response.data && response.data.code === '200') {
          // 重新加载关系数据
          this.showAllRelationships();
          alert('删除成功');
        } else {
          alert((response.data && response.data.msg) || '删除失败');
        }
      } catch (e) {
        console.error('删除关系数据出错:', e);
        alert('网络错误，请稍后重试');
      }
    },
    
    // 显示添加新成员对话框
    showAddPersonDialog() {
      this.isNewPerson = true;
      this.editingPerson = {
        personId: null,
        genealogyId: this.selectedGenealogyId,
        userId: parseInt(this.userId),
        name: '',
        sex: '',
        birthDateStr: '',
        deathDateStr: '',
        avatar: ''
      };
      console.log('初始化新成员数据:', this.editingPerson);
      this.showPersonDialog = true;
    },
    
    // 显示编辑成员对话框
    showEditPersonDialog(person) {
      this.isNewPerson = false;
      // 创建一个新对象，避免直接修改原对象
      this.editingPerson = {
        personId: person.personId,
        genealogyId: person.genealogyId,
        userId: person.userId,
        name: person.name,
        sex: person.sex,
        birthDateStr: person.birthDate ? new Date(person.birthDate).toISOString().split('T')[0] : '',
        deathDateStr: person.deathDate ? new Date(person.deathDate).toISOString().split('T')[0] : '',
        avatar: person.avatar || ''
      };
      this.showPersonDialog = true;
    },
    
    // 关闭人员编辑对话框
    closePersonDialog() {
      this.showPersonDialog = false;
    },
    
    // 保存人员信息
    async savePerson() {
      // 验证表单
      if (!this.editingPerson.name || !this.editingPerson.sex) {
        alert('请填写必要的人员信息（姓名和性别）');
        return;
      }
      
      try {
        // 准备要提交的数据
        const personData = {
          personId: this.editingPerson.personId,
          genealogyId: this.editingPerson.genealogyId,
          userId: parseInt(this.editingPerson.userId || this.userId),
          name: this.editingPerson.name,
          sex: this.editingPerson.sex,
          birthDate: this.editingPerson.birthDateStr ? new Date(this.editingPerson.birthDateStr).toISOString() : null,
          deathDate: this.editingPerson.deathDateStr ? new Date(this.editingPerson.deathDateStr).toISOString() : null,
          avatar: this.editingPerson.avatar
        };
        
        console.log('准备提交的人员数据:', personData);
        
        let response;
        
        if (this.isNewPerson) {
          // 添加新成员
          console.log('正在发送添加请求...');
          response = await axios.post('http://localhost:8080/genealogyPerson/add', personData, {
            timeout: 5000,
            headers: {
              'Content-Type': 'application/json'
            }
          });
          console.log('添加请求响应:', response);
        } else {
          // 更新现有成员信息
          console.log('正在发送更新请求...');
          response = await axios.put('http://localhost:8080/genealogyPerson/update', personData, {
            timeout: 5000,
            headers: {
              'Content-Type': 'application/json'
            }
          });
          console.log('更新请求响应:', response);
        }
        
        if (response.data && response.data.code === '200') {
          // 关闭对话框
          this.closePersonDialog();
          // 重新加载人员数据
          this.showPersonInfo();
          alert(this.isNewPerson ? '添加成功' : '更新成功');
        } else {
          alert((response.data && response.data.msg) || '操作失败');
        }
      } catch (e) {
        console.error('保存人员数据出错:', e);
        if (e.response) {
          console.error('错误响应数据:', e.response.data);
          console.error('错误状态码:', e.response.status);
          alert(`网络错误 (${e.response.status}): ${e.response.data.message || '未知错误'}`);
        } else if (e.request) {
          console.error('请求已发送但未收到响应');
          alert('服务器未响应，请检查后端服务是否正常运行');
        } else {
          console.error('请求配置错误:', e.message);
          alert(`请求错误: ${e.message}`);
        }
      }
    },
    
    // 确认删除成员
    confirmDeletePerson(person) {
      if (confirm(`确定要删除成员 ${person.name} 吗？这将同时删除与该成员相关的所有事件和关系记录。`)) {
        this.deletePerson(person.personId);
      }
    },
    
    // 删除成员
    async deletePerson(personId) {
      try {
        const response = await axios.delete(`http://localhost:8080/genealogyPerson/deleteById/${personId}`, {
          timeout: 5000
        });
        
        if (response.data && response.data.code === '200') {
          // 重新加载人员数据
          this.showPersonInfo();
          alert('删除成功');
        } else {
          alert((response.data && response.data.msg) || '删除失败');
        }
      } catch (e) {
        console.error('删除人员数据出错:', e);
        alert('网络错误，请稍后重试');
      }
    },
    
    // 显示添加新事件对话框
    showAddEventDialog() {
      if (!this.selectedGenealogyId || this.personList.length === 0) {
        alert('请先选择家族并确保有家族成员');
        return;
      }
      
      this.isNewEvent = true;
      const now = new Date();
      const dateTimeStr = now.toISOString().slice(0, 16); // 格式化为 yyyy-MM-ddThh:mm
      
      this.editingEvent = {
        eventId: null,
        personId: '',
        eventType: '',
        eventTimeStr: dateTimeStr,
        description: '',
        eventAttachment: ''
      };
      this.showEventDialog = true;
    },
    
    // 显示编辑事件对话框
    showEditEventDialog(event) {
      this.isNewEvent = false;
      
      // 格式化日期时间为HTML datetime-local输入格式
      let eventTimeStr = '';
      if (event.eventTime) {
        const date = new Date(event.eventTime);
        eventTimeStr = date.toISOString().slice(0, 16); // 格式化为 yyyy-MM-ddThh:mm
      }
      
      // 创建一个新对象，避免直接修改原对象
      this.editingEvent = {
        eventId: event.eventId,
        personId: event.personId,
        eventType: event.eventType,
        eventTimeStr: eventTimeStr,
        description: event.description || '',
        eventAttachment: event.eventAttachment || ''
      };
      
      this.showEventDialog = true;
    },
    
    // 关闭事件编辑对话框
    closeEventDialog() {
      this.showEventDialog = false;
    },
    
    // 保存事件
    async saveEvent() {
      // 验证表单
      if (!this.editingEvent.personId || !this.editingEvent.eventType) {
        alert('请选择关联人员和事件类型');
        return;
      }
      
      try {
        // 准备要提交的数据
        const eventData = {
          eventId: this.editingEvent.eventId,
          personId: this.editingEvent.personId,
          eventType: this.editingEvent.eventType,
          eventTime: this.editingEvent.eventTimeStr ? new Date(this.editingEvent.eventTimeStr).toISOString() : null,
          description: this.editingEvent.description,
          eventAttachment: this.editingEvent.eventAttachment
        };
        
        console.log('准备提交的事件数据:', eventData);
        
        let response;
        
        if (this.isNewEvent) {
          // 添加新事件
          console.log('正在发送添加请求...');
          response = await axios.post('http://localhost:8080/personEvent/add', eventData, {
            timeout: 5000,
            headers: {
              'Content-Type': 'application/json'
            }
          });
          console.log('添加请求响应:', response);
        } else {
          // 更新现有事件信息
          console.log('正在发送更新请求...');
          response = await axios.put('http://localhost:8080/personEvent/update', eventData, {
            timeout: 5000,
            headers: {
              'Content-Type': 'application/json'
            }
          });
          console.log('更新请求响应:', response);
        }
        
        if (response.data && response.data.code === '200') {
          // 关闭对话框
          this.closeEventDialog();
          // 重新加载事件数据
          this.showAllEvents();
          alert(this.isNewEvent ? '添加成功' : '更新成功');
        } else {
          alert((response.data && response.data.msg) || '操作失败');
        }
      } catch (e) {
        console.error('保存事件数据出错:', e);
        if (e.response) {
          console.error('错误响应数据:', e.response.data);
          console.error('错误状态码:', e.response.status);
          alert(`网络错误 (${e.response.status}): ${e.response.data.message || '未知错误'}`);
        } else if (e.request) {
          console.error('请求已发送但未收到响应');
          alert('服务器未响应，请检查后端服务是否正常运行');
        } else {
          console.error('请求配置错误:', e.message);
          alert(`请求错误: ${e.message}`);
        }
      }
    },
    
    // 确认删除事件
    confirmDeleteEvent(event) {
      if (confirm(`确定要删除"${this.getPersonName(event.personId)}"的"${event.eventType}"事件吗？`)) {
        this.deleteEvent(event.eventId);
      }
    },
    
    // 删除事件
    async deleteEvent(eventId) {
      try {
        const response = await axios.delete(`http://localhost:8080/personEvent/deleteById/${eventId}`, {
          timeout: 5000
        });
        
        if (response.data && response.data.code === '200') {
          // 重新加载事件数据
          this.showAllEvents();
          alert('删除成功');
        } else {
          alert((response.data && response.data.msg) || '删除失败');
        }
      } catch (e) {
        console.error('删除事件数据出错:', e);
        alert('网络错误，请稍后重试');
      }
    },
    async loadGenealogyTreeData() {
      if (!this.selectedGenealogyId) {
        this.error = '未选择家谱';
        return;
      }
      
      this.loading = true;
      this.error = null;
      this.treeReady = false;
      this.treeData = [];
      
      try {
        // 先获取家谱成员
        const personResponse = await axios.get(`http://localhost:8080/genealogyPerson/selectByGenealogyId/${this.selectedGenealogyId}`);
        if (personResponse.data.code !== '200') {
          throw new Error(personResponse.data.msg || '获取家谱成员失败');
        }
        
        this.personList = personResponse.data.data || [];
        
        // 如果没有成员，直接返回
        if (this.personList.length === 0) {
          this.treeReady = true;
          this.loading = false;
          return;
        }
        
        // 获取家谱树
        const response = await axios.get(`http://localhost:8080/family-tree/${this.selectedGenealogyId}`);
        
        if (response.data && response.data.code === '200') {
          console.log('获取到的家谱树数据:', response.data.data);
          
          // 设置树数据
          this.treeData = response.data.data || [];
          
          // 记录日志以便调试
          console.log('处理后的家谱树数据:', this.treeData);
          console.log('家谱树节点数量:', this.treeData.length);
          
          if (this.treeData.length > 0) {
            // 记录第一个节点的详细信息
            console.log('第一个节点详情:', JSON.stringify(this.treeData[0], null, 2));
          }
          
          // 检查是否所有成员都包含在树中
          const treeMembers = new Set();
          
          // 递归收集树中的所有成员ID
          const collectMemberIds = (nodes) => {
            if (!nodes) return;
            
            for (const node of nodes) {
              if (node.member) {
                treeMembers.add(node.member.personId);
              }
              if (node.spouse) {
                treeMembers.add(node.spouse.personId);
              }
              if (node.children && node.children.length > 0) {
                collectMemberIds(node.children);
              }
            }
          };
          
          collectMemberIds(this.treeData);
          
          console.log('树中包含的成员数量:', treeMembers.size);
          console.log('总成员数量:', this.personList.length);
          
          // 检查是否有成员未包含在树中
          const missingMembers = this.personList.filter(person => !treeMembers.has(person.personId));
          
          if (missingMembers.length > 0) {
            console.log('发现未包含在树中的成员:', missingMembers);
            
            // 为每个未包含的成员创建一个独立节点
            for (const member of missingMembers) {
              this.treeData.push({
                member: member,
                children: []
              });
            }
          }
          
          this.treeReady = true;
        } else {
          this.error = (response.data && response.data.msg) || '加载家谱树失败';
        }
      } catch (error) {
        console.error('加载家谱树错误:', error);
        this.error = '加载家谱树失败: ' + (error.message || '未知错误');
      } finally {
        this.loading = false;
      }
    },
    calculateChildrenLines(treeRows) {
      // 为每个有子女的单元计算子女连接线的宽度
      for (let i = 0; i < treeRows.length - 1; i++) {
        const currentRow = treeRows[i];
        const nextRow = treeRows[i + 1];
        
        for (const unit of currentRow) {
          if (unit.hasChildren && unit.children.length > 0) {
            // 找出下一代中属于这个单元子女的所有单元
            const childUnits = [];
            
            for (const childUnit of nextRow) {
              const persons = [];
              if (childUnit.left) persons.push(childUnit.left);
              if (childUnit.right) persons.push(childUnit.right);
              if (childUnit.single) persons.push(childUnit.single);
              
              for (const person of persons) {
                if (unit.children.find(child => child.personId === person.personId)) {
                  childUnits.push(childUnit);
                  break;
                }
              }
            }
            
            // 计算子女单元的总宽度（假设每个单元宽度为160px，间距为20px）
            const unitWidth = 160;
            const unitMargin = 20;
            unit.childrenWidth = childUnits.length * (unitWidth + unitMargin) - unitMargin;
          }
        }
      }
    },
    searchGenealogies() {
      // 搜索逻辑，已在计算属性 filteredGenealogies 中实现
    },
    showCreateGenealogyForm() {
      this.showGenealogyForm = true;
    },
    closeGenealogyForm() {
      this.showGenealogyForm = false;
      // 重置表单
      this.newGenealogy = {
        genealogyName: '',
        description: ''
      };
    },
    zoomIn() {
      this.zoomLevel += 0.1;
    },
    zoomOut() {
      this.zoomLevel -= 0.1;
    },
    resetZoom() {
      this.zoomLevel = 1;
    }
  },
  computed: {
    // 过滤事件列表
    filteredEvents() {
      if (!this.eventSearchQuery) {
        return this.allEvents;
      }
      
      const query = this.eventSearchQuery.toLowerCase();
      return this.allEvents.filter(event => {
        const personName = this.getPersonName(event.personId).toLowerCase();
        const eventType = (event.eventType || '').toLowerCase();
        const eventDesc = (event.description || '').toLowerCase();
        
        return personName.includes(query) || 
               eventType.includes(query) || 
               eventDesc.includes(query);
      });
    },
    
    // 过滤关系列表
    filteredRelationships() {
      if (!this.relationshipSearchQuery) {
        return this.relationships;
      }
      
      const query = this.relationshipSearchQuery.toLowerCase();
      return this.relationships.filter(relationship => {
        const person1Name = this.getPersonName(relationship.personId1).toLowerCase();
        const person2Name = this.getPersonName(relationship.personId2).toLowerCase();
        const relationType = (relationship.relationshipType || '').toLowerCase();
        
        return person1Name.includes(query) || 
               person2Name.includes(query) || 
               relationType.includes(query);
      });
    },
    
    // 过滤人员列表
    filteredPersons() {
      if (!this.personSearchQuery) return this.personList;
      
      const query = this.personSearchQuery.toLowerCase();
      return this.personList.filter(person => {
        return person.name && person.name.toLowerCase().includes(query);
      });
    },
    filteredGenealogies() {
      if (!this.genealogySearchQuery) return this.genealogies;
      
      const query = this.genealogySearchQuery.toLowerCase();
      return this.genealogies.filter(genealogy => {
        const nameMatch = genealogy.genealogyName && genealogy.genealogyName.toLowerCase().includes(query);
        const descMatch = genealogy.description && genealogy.description.toLowerCase().includes(query);
        return nameMatch || descMatch;
      });
    }
  }
}
</script>

<style scoped>
.genealogy-page {
  display: flex;
  min-height: 100vh;
  width: 100vw;
}

/* 左侧操作区域样式 */
.sidebar {
  width: 250px;
  background-color: #f0f0f0;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ddd;
}

.sidebar-header {
  padding: 1.5rem;
  border-bottom: 1px solid #ddd;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 1.25rem;
  color: #333;
}

.sidebar-menu {
  flex: 1;
  padding: 1rem 0;
}

.menu-item {
  padding: 0.75rem 1.5rem;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.menu-item:hover {
  background-color: #e0e0e0;
}

.menu-item.active {
  background-color: #d0d0d0;
  border-left: 4px solid #0061ff;
}

.menu-item i {
  margin-right: 0.75rem;
  width: 20px;
  text-align: center;
  color: #555;
}

.sidebar-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid #ddd;
}

/* 侧边栏的返回按钮使用蓝色主色调 */
.sidebar-footer .btn-primary {
  background-color: #0061ff;
  border-color: #0061ff;
  width: 100%;
  transition: all 0.3s ease;
}

.sidebar-footer .btn-primary:hover {
  background-color: #0052d9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 97, 255, 0.3);
}

/* 右侧展示区域样式 */
.content-area {
  flex: 1;
  background-color: #e6f2ff;
  display: flex;
  flex-direction: column;
}

.content-header {
  padding: 1rem 2rem;
  border-bottom: 1px solid #ddd;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

/* 顶部返回按钮 */
.back-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #0061ff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  position: absolute;
  left: 1rem;
  top: 1rem;
  z-index: 10;
  box-shadow: 0 2px 5px rgba(0,97,255,0.3);
}

.back-button:hover {
  background-color: #0052d9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,97,255,0.4);
}

.back-button i {
  color: white;
  font-size: 1.2rem;
}

.content-body {
  flex: 1;
  padding: 2rem;
  overflow: auto;
}

/* 家谱树样式 */
.genealogy-tree-container {
  width: 100%;
  overflow-x: auto;
  padding: 20px 0;
}

.genealogy-tree {
  padding: 20px;
  overflow-x: auto;
  min-height: 500px;
}

.tree-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tree-node {
  margin-bottom: 30px;
}

.tree-generation {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tree-family-unit {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tree-person-container {
  display: flex;
  align-items: center;
}

.tree-connector {
  width: 50px;
  height: 2px;
  background-color: #666;
}

.tree-person {
  width: 150px;
  padding: 10px;
  border-radius: 5px;
  margin: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.tree-person.male {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.tree-person.female {
  background-color: #fff0f6;
  border: 1px solid #ffadd2;
}

.person-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  overflow: hidden;
}

.person-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.person-avatar i {
  font-size: 24px;
}

.person-avatar i.fa-male {
  color: #1890ff;
}

.person-avatar i.fa-female {
  color: #eb2f96;
}

.person-info {
  text-align: center;
}

.person-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.person-dates {
  font-size: 12px;
  color: #666;
}

.children-connector {
  height: 30px;
  display: flex;
  justify-content: center;
}

.vertical-line {
  width: 2px;
  height: 100%;
  background-color: #666;
}

.children-container {
  display: flex;
  justify-content: center;
}

.child-branch {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 10px;
}

.horizontal-line {
  width: 50px;
  height: 2px;
  background-color: #666;
  margin-bottom: 10px;
}

/* 家族列表样式 */
.family-placeholder {
  text-align: center;
  color: #999;
  padding: 3rem;
}

.family-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-top: 1.5rem;
}

.family-item {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.family-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.family-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #f0f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
  flex-shrink: 0;
}

.family-icon i {
  font-size: 1.25rem;
  color: #0061ff;
}

.add-icon {
  background-color: #e6f7e6;
}

.add-icon i {
  color: #28a745;
}

.family-info {
  flex: 1;
}

.family-info h4 {
  margin: 0;
  font-size: 1.1rem;
  color: #333;
}

.family-info p {
  margin: 0.25rem 0 0;
  font-size: 0.875rem;
  color: #777;
}

.family-info .description {
  margin-top: 0.5rem;
  color: #555;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .genealogy-page {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
  }
  
  .content-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .content-actions {
    margin-top: 1rem;
  }
  
  .family-list {
    grid-template-columns: 1fr;
  }
}

.tree-section-title {
  text-align: center;
  margin-bottom: 10px;
  color: #333;
}

.tree-node-group {
  margin-bottom: 50px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.tree-node-title {
  text-align: center;
  margin-bottom: 20px;
}

.tree-node-title .badge {
  font-size: 14px;
  padding: 8px 15px;
}

/* 统一家族树样式 */
.unified-tree-container {
  padding: 30px;
  overflow: auto;
  width: 100%;
  min-height: 500px;
  max-height: 80vh;
  position: relative;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}

.family-members-container {
  display: flex;
  flex-direction: column;
  gap: 40px;
  min-width: fit-content;
  padding: 20px;
  transition: transform 0.3s ease;
}

/* 添加缩放控制按钮 */
.tree-controls {
  position: absolute;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 10px;
  z-index: 10;
}

.tree-control-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: white;
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.tree-control-btn:hover {
  background-color: #f0f0f0;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.tree-control-btn i {
  font-size: 18px;
  color: #555;
}

.tree-person-container {
  display: flex;
  align-items: center;
}

.tree-connector {
  width: 50px;
  height: 2px;
  background-color: #333;
  margin: 0 10px;
}

.tree-person {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  min-width: 120px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.tree-person.male {
  background-color: #e6f7ff;
  border: 2px solid #1890ff;
}

.tree-person.female {
  background-color: #fff0f6;
  border: 2px solid #eb2f96;
}

</style> 